import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { CreateMenuDto } from './dto/create-menu.dto';
import { UpdateMenuDto } from './dto/update-menu.dto';
import { Menu } from './entities/menu.entity';
import { IsNull, Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { MenuVo } from './vo/select-menu.vo';

@Injectable()
export class MenuService {
  constructor(
    @InjectRepository(Menu)
    private menuRepository: Repository<Menu>
    ) {}
    // 新增菜单
  async create(createMenuDto: CreateMenuDto) {
    console.log('---------', createMenuDto)
    return await this.menuRepository.insert(createMenuDto);
  }
  // 获取菜单树形下拉列表
  async findMenuWithSelectTree() {
    try {
      const result: any = await  this.menuRepository.find({
        select: {
          menu_id: true,
          menu_name: true,
          parent_id: true,
          order_num: true,
      },
      where: {
        delete_time: IsNull()
      }
      });
      const menuList: any = result
        .filter((menu) => menu.parent_id == 0)
        .map((menu) => {
            menu.children = this.getChildren(menu, result);
        return menu;
      })
      .sort((a: any, b: any) => a.order_num - b.order_num);
      return [{
        menu_id: 0,
        menu_name: '根目录',
        parent_id: 0,
        order_num: 0,
        children: menuList
      }]
    } catch (error) {
      throw new HttpException(error.toString(), HttpStatus.BAD_REQUEST);
    }
  }
  // 获取所有菜单列表
  async findMenuWithTree() {
    try {
      const result: Array<MenuVo> = await  this.menuRepository.find({
        where: {
          delete_time: IsNull()
        }
      }) as Array<MenuVo>;
      const menuList: Array<MenuVo> = result
        .filter((menu) => menu.parent_id == 0)
        .map((menu) => {
            menu.children = this.getChildren(menu, result);
        return menu;
      })
      .sort((a: any, b: any) => a.order_num - b.order_num);
      return menuList;
    } catch (error) {
      throw new HttpException(error.toString(), HttpStatus.BAD_REQUEST);
    }
  }
  // 查询菜单详情
  findOne(id: number) {
    return this.menuRepository.findOne({
      where: { menu_id: id }
    });
  }
  // 修改菜单
  update(id: number, updateMenuDto: UpdateMenuDto) {
    return this.menuRepository.update(id, updateMenuDto);
  }
  // 删除菜单
  remove(id: number) {
    return this.menuRepository.update(id, {
      delete_time: Date.now()
    });
  }
  // 获取子级菜单
  getChildren(currentMenu, list) {
    return list
      .filter((menu) => {
        return menu.parent_id == currentMenu.menu_id;
      })
      .map((menu) => {
        menu.children = this.getChildren(menu, list);
        return menu;
      })
      .sort((a: any, b: any) => a.order_num - b.order_num);
  }
}
